// 云函数入口文件
const cloud = require("wx-server-sdk");
const MD5 = require("Md5");
cloud.init({env: cloud.DYNAMIC_CURRENT_ENV});
const db = cloud.database();
const CustomError = require("./CustomError");

// 云函数入口函数
exports.main = async (event, context) => {
    return modules[event.actionName](event)
}

const modules = {
    /*
    获取无限制小程序码
    * */
    getUnlimitedCode: async function (event) {
        try {
            let {path} = event.params;
            let {OPENID} = cloud.getWXContext();
            let md5 = MD5.hexMD5(path);
            const collection = await db.collection("wxacode");
            const getCodeRecord = await collection.where({
                md5: md5
            }).count();
            if (getCodeRecord.total === 0) {
                await collection.add({
                    data: {
                        openId: OPENID,
                        path: path,
                        md5: md5,
                        createTime: new Date().getTime()
                    }
                })
            }
            let res = await cloud.openapi.wxacode.getUnlimited({
                scene: md5,
                page: "pages/loading/loading"
            })
            return {status: 0, data: {buffer: res.buffer}};
        } catch (e) {
            console.error("======" + event.actionName + "======");
            console.error(e);
            return new CustomError(e, event.actionName)
        }
    },

    /*
    * md5兑换数据
    * */
    getQueryCodeOptions: async function (event) {
        try {
            const {md5} = event.params
            const res = await db.collection("wxacode").where({
                md5: md5
            }).get();
            if (res.data.length === 0) {
                throw new Error("无效的md5")
            } else {
                return {
                    status: 0,
                    data: Object.assign(res.data[0], {total: res.data.length})
                }
            }
        } catch (e) {
            console.error("======" + event.actionName + "======");
            console.error(e);
            return new CustomError(e, event.actionName)
        }
    },

    /*
    * 发送模板消息
    * */
    sendMessage: async function (event) {
        try {
            const {params} = event;
            await cloud.openapi.subscribeMessage.send({
                touser: params.openId,
                page: params.page,
                lang: "zh_CN",
                data: params.data,
                templateId: params.templateId,
                miniprogramState: params.miniprogramState
            })
            return {status: 0}
        } catch (e) {
            console.error("======" + event.actionName + "======");
            console.error(e);
            return new CustomError(e, event.actionName)
        }
    }
}

